﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WIC_Data_Manager
{
    public partial class fManager : Form
    {
        bool Writer;
        string YearShowing;
        public fManager(bool write)
        {
            InitializeComponent();
            Writer = write;
            YearShowing = "";
            usernameToolStripMenuItem.Text = Globals.CurrentlyLoggedIn;
        }

        private void fManager_FormClosed(object sender, FormClosedEventArgs e)
        {
            Program.Splash.Show();
        }

        delegate void UpdateDelegate(string year);

        public void UpdateByYear(string year)
        {

            YearShowing = year;

            if (tcManager.SelectedTab.Name == "tabPage1")
            {
                dgvParticipation.Rows.Clear();

                List<string> rows = Globals.DataBases.Participation.LargeQuery("SELECT * FROM y" + year);

                for (int i = 0; i < rows.Count; i++)
                {
                    dgvParticipation.Rows.Add(rows[i].Split(' '));
                }
            }
        }

        void tsmiYear_OnClick(object sender, EventArgs e)
        {

            ToolStripDropDownItem YearClicked = (ToolStripDropDownItem)sender;
            YearShowing = YearClicked.Text;

            if (tcManager.SelectedTab.Name == "tabPage1")
            {
                dgvParticipation.Rows.Clear();
                List<string> rows = Globals.DataBases.Participation.LargeQuery("SELECT * FROM y" + YearClicked.Text);

                for (int i = 0; i < rows.Count; i++)
                {
                    dgvParticipation.Rows.Add(rows[i].Split(' '));
                }

            }
            else
            {
                dgvInitiation.Rows.Clear();
                List<string> rows = Globals.DataBases.Initiation.LargeQuery("SELECT * FROM y" + YearClicked.Text);

                for (int i = 0; i < rows.Count; i++)
                {
                    dgvInitiation.Rows.Add(rows[i].Split(' '));
                }
            }

        }

        void tsmiMonth_OnClick(object sender, EventArgs e)
        {
            
            ToolStripDropDownItem MonthClicked = (ToolStripDropDownItem)sender;

            ToolStripItem YearClicked = MonthClicked.OwnerItem;
            YearShowing = YearClicked.Text;

            if (tcManager.SelectedTab.Name == "tabPage1")
            {
                dgvParticipation.Rows.Clear();
                List<string> rows = Globals.DataBases.Participation.LargeQuery("SELECT * FROM y" + YearClicked.Text + " WHERE Month='" + MonthClicked.Text + "'");

                for (int i = 0; i < rows.Count; i++)
                {
                    dgvParticipation.Rows.Add(rows[i].Split(' '));
                }

            }
            else
            {
                dgvInitiation.Rows.Clear();
                List<string> rows = Globals.DataBases.Initiation.LargeQuery("SELECT * FROM y" + YearClicked.Text + " WHERE Month='" + MonthClicked.Text + "'");

                for (int i = 0; i < rows.Count; i++)
                {
                    dgvInitiation.Rows.Add(rows[i].Split(' '));
                }
            }
        }

        private void fManager_Load(object sender, EventArgs e)
        {
            
            Globals.DataBases.Participation.Connect();
            Globals.DataBases.Initiation.Connect();
            List<string> years = Globals.DataBases.Participation.LargeQuery("SHOW TABLES");
          
            foreach (string year in years)
            {
                string tempYear = year.TrimStart('y');
                yearToolStripMenuItem.DropDownItems.Add(tempYear, null, new EventHandler(tsmiYear_OnClick));
            }
            foreach (ToolStripMenuItem yearItem in yearToolStripMenuItem.DropDownItems)
            {
                for (int i = 0; i < 12; i++)
                {
                    yearItem.DropDownItems.Add(Globals.Months[i], null, new EventHandler(tsmiMonth_OnClick));
                }
            }
            if (!Writer)
            {
                addToolStripMenuItem.Enabled = false;
                editToolStripMenuItem.Enabled = false;
            }
        }

        private void clinicToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (YearShowing == "")
            {
                MessageBox.Show("Please select a year before adding a new clinic", "WIC Data Manager Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else
            {
                Globals.Forms.AddClinicScreen = new fAddClinic(YearShowing);
                Globals.Forms.AddClinicScreen.ShowDialog();
            }
        }

        private void dgvParticipation_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            string query = "";
            string msg = String.Format("Cell at row {0}, column {1} value changed",e.RowIndex, e.ColumnIndex);
            string ColumnName = dgvParticipation.Columns[e.ColumnIndex].Name;
            string ValueChanged = (string)(dgvParticipation.Rows[e.RowIndex].Cells[ColumnName].Value);
            string Key = (string)(dgvParticipation.Rows[e.RowIndex].Cells["Key"].Value);
            if (ColumnName == "NonBreastfeeding" || ColumnName == "Breastfeeding" || ColumnName == "ID" || ColumnName == "Prenatal")
            {
                if (!Globals.IsNumeric(ValueChanged))
                {
                    MessageBox.Show("One or more datafields are incorrect", "WIC Data Manager Data Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                }
                else
                {
                    query = String.Format("UPDATE y{0} SET {1}={2} WHERE `Key`={3}", Globals.Forms.ManagerScreen.YearShowing, ColumnName, ValueChanged, Key);
                }
            }
            else
            {
                if (Globals.IsNumeric(query))
                {
                    MessageBox.Show("One or more datafields are incorrect", "WIC Data Manager Data Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                }
                else
                {
                    if (ColumnName == "ClinicName") ColumnName = "Name";
                    query = String.Format("UPDATE y{0} SET {1}='{2}' WHERE `Key`={3}", Globals.Forms.ManagerScreen.YearShowing, ColumnName, ValueChanged, Key);
                }
            }
            //MessageBox.Show(msg+"\n'"+query+"'", "Cell Value Changed");
            if (query != "") Globals.DataBases.Participation.SimpleQuery(query);
            this.BeginInvoke(new UpdateDelegate(UpdateByYear),YearShowing);
        }

        private void dgvInitiation_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            string query = "";
            string msg = String.Format("Cell at row {0}, column {1} value changed", e.RowIndex, e.ColumnIndex);
            string ColumnName = dgvInitiation.Columns[e.ColumnIndex].Name;
            string ValueChanged = (string)(dgvInitiation.Rows[e.RowIndex].Cells[ColumnName].Value);
            string Key = (string)(dgvInitiation.Rows[e.RowIndex].Cells["iKey"].Value);
            if (ColumnName == "iID" || ColumnName == "iPercent")
            {
                if (!Globals.IsNumeric(ValueChanged))
                {
                    MessageBox.Show("One or more datafields are incorrect", "WIC Data Manager Data Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                }
                else
                {
                    query = String.Format("UPDATE y{0} SET {1}={2} WHERE `Key`={3}", Globals.Forms.ManagerScreen.YearShowing, ColumnName.TrimStart('i'), ValueChanged, Key);
                }
            }
            else
            {
                if (Globals.IsNumeric(query))
                {
                    MessageBox.Show("One or more datafields are incorrect", "WIC Data Manager Data Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                }
                else
                {
                    query = String.Format("UPDATE y{0} SET {1}='{2}' WHERE `Key`={3}", Globals.Forms.ManagerScreen.YearShowing, ColumnName.TrimStart('i'), ValueChanged, Key);
                }
            }
            //MessageBox.Show(msg+"\n'"+query+"'", "Cell Value Changed");
            if (query != "") Globals.DataBases.Initiation.SimpleQuery(query);
            this.BeginInvoke(new UpdateDelegate(UpdateByYear), YearShowing);
        }

        private void logOutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Globals.Forms.ManagerScreen.Close();
            Program.Splash.ClearFields();
        }
    }
}
